<?php
/**
 * Localization Auto Complete
 * Return a json file according to send caracters
 * -> First Look Up to Region
 * -> Then State
 * -> Send City
 *
 */

use Fox\Dao\SqlFragment;
use Fox\Common\Localization\Region;

$xview = Xview::instance();
$terms = $xview->val('q');
$callback = $xview->val('callback');
$result = array();
// Regions
$query = Fox\Dao::infos(Region::className())->handle()->createQueryBuilder();
$query->select('regid AS id','name')
		->from('regions','t');
$fragment = new SqlFragment('name LIKE ?',array("%$terms%"));
$regions = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
foreach($regions as $region) {
	$result[] = array('id' => 'r_'.$region['id'],'name' =>$region['name']);
}
// Groups
$query = Fox\Dao::infos(Region::className())->handle()->createQueryBuilder();
$query->select('reggrpid AS id','name')
		->from('region_groups','t');
$fragment = new SqlFragment('name LIKE ?',array("%$terms%"));
$groups = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
foreach($groups as $group) {
	$result[] = array('id' => 'g_'.$group['id'],'name' => $group['name']);
}
// States
$query = Fox\Dao::infos(Region::className())->handle()->createQueryBuilder();
$query->select('regsubid AS id','name')
		->from('region_subs','t');
$fragment = new SqlFragment('name LIKE ?',array("%$terms%"));
$subs = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
foreach($subs as $sub) {
	$result[] = array('id' => 's_'.$sub['id'],'name' => $sub['name']);
}

# JSON-encode the response
$json_response = Fox\Utilities::jsonUTF8Encode($result);

# Optionally: Wrap the response in a callback function for JSONP cross-domain support
if($callback) {
    $json_response = $callback . '(' . $json_response . ')';
}

# Return the response
echo $json_response;